/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

const fs = require('fs');

function parse_bin_txt_file(path) {
    const buffer = fs.readFileSync(path);
    // The .bin.txt file is a hex dump, e.g. "0a 00 00 00 68 65 6c 6c 6f 20 77 6f 72 6c 64"
    // We want to parse it into a Buffer of bytes.
    // Remove comments and whitespace, split by spaces, and parse hex.
    const lines = buffer.toString('utf-8').split('\n');
    let hexStr = '';
    for (let line of lines) {
        // Remove comments (after #)
        const idx = line.indexOf('#');
        if (idx !== -1) {
            line = line.slice(0, idx);
        }
        hexStr += line + ' ';
    }
    // Split by whitespace, filter empty, parse as hex
    const bytes = hexStr
        .split(/\s+/)
        .filter(x => x.length > 0)
        .map(x => parseInt(x, 16));
    return Buffer.from(bytes);
}

module.exports = {
    parse_bin_txt_file
}
